﻿Ext.require([
    'Ext.form.*',
    'Ext.window.MessageBox',
    'Ext.tip.*'
]);

Ext.onReady(function () {

    Ext.tip.QuickTipManager.init();

    var f = Ext.create('Ext.form.Panel', {
        frame: true,
        bodyPadding: 10,
        bodyBorder: true,

        fieldDefaults: {
            msgTarget: 'side',
            labelWidth: 75
        },

        defaults: {
            anchor: '100%'
        },

        items: [
            {
                xtype: 'textfield',
                name: 'UserName',
                fieldLabel: 'Username'
            },
            {
                xtype: 'textfield',
                name: 'Password',
                fieldLabel: 'Password',
                inputType: 'password'
            },
            {
                xtype: 'checkboxfield',
                name: 'RememberMe',
                boxLabel: 'Remember me'
            }
        ],

        buttons: [
            {
                text: 'Log On',
                handler: function () {

                    f.getForm().submit({
                        method: 'POST',
                        url: '/Account/LogOn',
                        clientValidation: true,

                        success: function (form, action) {

                            if (action.result.data) {

                                // Set in session storage
                                sessionStorage.setItem("applicationUser", Ext.encode(action.result.data));

                                // Redirect to the main location
                                window.location = '/';
                            }
                            else {

                                Ext.MessageBox.show({
                                    title: 'Log On failed',
                                    msg: action.result.msg,
                                    width: 300,
                                    buttons: Ext.MessageBox.OK
                                });

                            }
                        },

                        failure: function (form, action) {
                        }

                    });

                }
            }
        ]

    });

    // TODO: Set as not resizable
    Ext.create('Ext.window.Window', {
        title: 'Log On',
        resizable : false,
        height: 170,
        width: 300,
        border: false,
        layout: 'fit',
        items: [f]
    }).show();

});